interface FlatItem {
  id: number;
  parent?: number;
  // 其他可能的属性
  [key: string]: any;
}

export class TreeUtils {
  static toTree(items: FlatItem[]): FlatItem[] {
    const map: { [id: number]: FlatItem } = {};
    const roots: FlatItem[] = [];

    items.forEach((item) => {
      map[item.id] = { ...item };
    });

    items.forEach((item) => {
      if (item.parent) {
        const parent = map[item.parent];
        if (parent) {
          (parent.children || (parent.children = [])).push(map[item.id]);
        }
      } else {
        roots.push(map[item.id]);
      }
    });

    return roots;
  }
}
